package com.zx.dsptuneup_TriMic.network;

import android.app.Activity;
import android.content.Intent;
import android.net.ParseException;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;

import androidx.annotation.NonNull;

import com.blankj.utilcode.util.ActivityUtils;
import com.hjq.toast.ToastUtils;
import com.zx.dsptuneup_TriMic.App;
import com.zx.dsptuneup_TriMic.R;
import com.zx.dsptuneup_TriMic.activity.HomeListActivity;
import com.zx.dsptuneup_TriMic.activity.LoginActivity;
import com.zx.dsptuneup_TriMic.bean.BasicResponse;
import com.google.gson.JsonParseException;
import com.jakewharton.retrofit2.adapter.rxjava2.HttpException;
import org.json.JSONException;
import java.io.InterruptedIOException;
import java.net.ConnectException;
import java.net.UnknownHostException;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

import static com.blankj.utilcode.util.ActivityUtils.startActivity;

/**
 * Created by window on 2018/3/13.
 */

public abstract class DefaultObserver<T extends BasicResponse> implements Observer<T> {

    public DefaultObserver() {
    }

    @Override
    public void onSubscribe(@NonNull Disposable d) {

    }

    @Override
    public void onNext(@NonNull T response) {
        if (response.getCode() == 200){
            onSuccess(response);
        }else{
            onFail(response);
        }
    }

    //请求成功后的处理
    protected abstract void onSuccess(T response);

    //服务器返回失败的处理
    protected void onFail(T response){
        String message = response.getMsg();

        if (TextUtils.isEmpty(message)) {
            ToastUtils.show(R.string.response_return_error);
        } else {
            ToastUtils.show(message);
        }
        if(response.getCode() == 200){

        }
    }


    //网络连接失败、网络连接超时、数据解析异常调用
    @Override
    public void onError(@NonNull Throwable e) {
        Log.e("222","onErroronErroronError");
        if (e instanceof HttpException) {     //   HTTP错误
            if (e instanceof HttpException) {     //   HTTP错误
                if(((HttpException) e).code() == 404 || ((HttpException) e).code() == 401) {
                    if(((HttpException) e).code() == 404){
                        onException(ExceptionReason.BAD_NETWORK);
                    }else {
                        onException(ExceptionReason.TOKEN_UPDATA);
                    }
                    jumpToLogin();
                }
            }
        } else if (e instanceof ConnectException || e instanceof UnknownHostException) {   //   连接错误
            onException(ExceptionReason.CONNECT_ERROR);
            jumpToLogin();
        } else if (e instanceof InterruptedIOException) {   //  连接超时
            onException(ExceptionReason.CONNECT_TIMEOUT);
            jumpToLogin();
        } else if (e instanceof JsonParseException
                || e instanceof JSONException
                || e instanceof ParseException) {   //  解析错误
            onException(ExceptionReason.PARSE_ERROR);
        } else {
            onException(ExceptionReason.UNKNOWN_ERROR);
        }
    }

    @Override
    public void onComplete() {

    }

    public void jumpToLogin() {
        Activity top = App.getTopActivity();
        if(top == null || top.getLocalClassName().contains("LoginActivity")){
            return;
        }
        top.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Intent intent = new Intent(top, LoginActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                //不能用此方法，因为找不到 topActivity
//                 startActivity(intent);
                top.startActivity(intent);
                // 因为先进入的HomeList再退到login,HomeList仍然存在
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        top.finish();
                    }
                },300);


            }
        });
    }

    /**
     * 请求网络失败原因
     */
    public enum ExceptionReason {
        /**
         * 解析数据失败
         */
        PARSE_ERROR,
        /**
         * 网络问题
         */
        BAD_NETWORK,
        /**
         * 连接错误
         */
        CONNECT_ERROR,
        /**
         * 连接超时
         */
        CONNECT_TIMEOUT,
        /**
         * 未知错误
         */
        UNKNOWN_ERROR,
        /**
         * token过期
         */
        TOKEN_UPDATA,
    }

    /**
     * 请求异常
     * @param reason
     */
    public void onException(ExceptionReason reason) {
        switch (reason) {
            case CONNECT_ERROR:
                ToastUtils.show(R.string.connect_error);
                break;

            case CONNECT_TIMEOUT:
                ToastUtils.show(R.string.connect_timeout);
                break;

            case BAD_NETWORK:
                ToastUtils.show(R.string.bad_network);
                break;

            case PARSE_ERROR:
                ToastUtils.show(R.string.parse_error);
                break;
            case TOKEN_UPDATA:
                ToastUtils.show(R.string.token_error);
                break;
            case UNKNOWN_ERROR:
            default:
                ToastUtils.show(R.string.unknown_error);
                break;
        }
    }
}
